﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing.Text;
using System.Drawing;

namespace HiStaff.iSystem
{
    public class SystemFont
    {
        [DllImport("gdi32.dll")]
        private static extern IntPtr AddFontMemResourceEx(IntPtr pbFont, uint cbFont, IntPtr pdv, [In] ref uint pcFonts);
        private static PrivateFontCollection pfc;
        public static Font FontSegoeUi
        {
            get
            {
                return GetFont(FontName.SegoeUi);
            }
        }
        public static Font FontSegoeUiSemiBold
        {
            get
            {
                return GetFont(FontName.SegoeUiSemiBold);
            }
        }
        public enum FontName
        {
            SegoeUi = 0,
            SegoeUiLight = 1,
            SegoeUiSemiBold = 2,
            SegoeUiSemiLight = 3,
        }

        public static Font GetFont(FontName font)
        {
            return GetFont(font, FontStyle.Regular);
        }
        public static Font GetFont(FontName font, FontStyle style)
        {
            return GetFont(font, style, 8.25f);
        }
        public static Font GetFont(FontName font, FontStyle style, float size)
        {
            if (pfc != null)
            {
                return new Font(pfc.Families[(int)font], size, style);
            }
            else
            {
                CargoPrivateFontCollection();
                return new Font(pfc.Families[(int)font], size, style);
            }
        }
        private static void CargoPrivateFontCollection()
        {
            pfc = new PrivateFontCollection();
            var lstResourceFont = new List<byte[]>();
            lstResourceFont.Add(Properties.Resources.segoeui); // 0. Segoe Ui
            lstResourceFont.Add(Properties.Resources.segoeuil); // 1. Segoe Ui Light
            lstResourceFont.Add(Properties.Resources.seguisbi); // 2. Segoe Ui SemiBold
            lstResourceFont.Add(Properties.Resources.seguisli); // 3. Segoe Ui SemiLight
            // Create the byte array and get its length
            foreach (var font in lstResourceFont)
            {
                byte[] fontArray = font;
                int dataLength = font.Length;


                // ASSIGN MEMORY AND COPY  BYTE[] ON THAT MEMORY ADDRESS
                IntPtr ptrData = Marshal.AllocCoTaskMem(dataLength);
                Marshal.Copy(fontArray, 0, ptrData, dataLength);


                uint cFonts = 0;
                AddFontMemResourceEx(ptrData, (uint)fontArray.Length, IntPtr.Zero, ref cFonts);


                //PASS THE FONT TO THE  PRIVATEFONTCOLLECTION OBJECT
                pfc.AddMemoryFont(ptrData, dataLength);

                //FREE THE  "UNSAFE" MEMORY
                Marshal.FreeCoTaskMem(ptrData);
            }
        }
    }
}
